//
//  HealthData.m
//  SpiritWalk
//
//  Created by 王鑫 on 16/3/14.
//  Copyright © 2016年 王鑫. All rights reserved.
//

#import "HealthData.h"

@implementation HealthData
-(void)getHealthAuthorization{
    self.healthStore = [[HKHealthStore alloc] init];
   // NSSet *shareObjectTypes = [NSSet setWithObjects:
                         //      [HKObjectType workoutType ], nil];
    // 允许读权限
    NSSet *readObjectTypes  = [NSSet setWithObjects:
                               [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning],
                               [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierFlightsClimbed],
                               [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount],
                               nil];
    if( [self.healthStore isProxy]){
        NSLog(@"------YES");
    }else{
        NSLog(@"------NO");
    };
    //HKQuantityTypeIdentifierDistanceWalkingRunning 步行加跑步距离
   // HKQuantityTypeIdentifierFlightsClimbed 楼层
  //  HKWorkoutTypeIdentifier 体能训练
    [ self.healthStore requestAuthorizationToShareTypes:nil readTypes:readObjectTypes completion:^(BOOL success, NSError *error) {
        if(success == YES){
            NSUserDefaults * userDefaults=[NSUserDefaults standardUserDefaults];
            NSString * healthAuthorization =[userDefaults objectForKey:@"healthAuthorization"];
            if ([healthAuthorization isEqualToString:@"YES"]) {
                NSLog(@"数据已经存储完毕了");
                
               // [self upDateStepCount];
            }else{
                [self createStepCount];
                
                [userDefaults setObject:@"YES" forKey:@"healthAuthorization"];
                NSLog(@"存储数据");
            }
           // NSLog(@"yes");
        }else{
          //  NSLog(@"no");
        }
    }];
}
-(void)upDateStepCount{
    NSLog(@"数据更新");
    self.manager=[CoreDataManager manager];
   // Health * healt=[[Health alloc] init];
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Health" inManagedObjectContext:self.manager.managedObjectContext];
    [fetchRequest setEntity:entity];
    NSDate *date = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd"];
    NSString *dateString = [dateFormatter stringFromDate:date];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"date=%@ ", dateString];
    [fetchRequest setPredicate:predicate];
    NSError *error = nil;
    NSArray *fetchedObjects = [self.manager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
       
    }
    for (Health * health in fetchedObjects) {
    //------------------------------------------------------------------------------
    NSArray * toDayArr=[dateString componentsSeparatedByString:@"-"];
    NSDate *startDate = [NSDate date];
    startDate=[NSDate distantPast];
    NSDateComponents *comp = [[NSDateComponents alloc]init];
    [comp setMonth:[toDayArr[1] integerValue]];
    [comp setDay:[toDayArr[2] integerValue]];
    [comp setYear:[toDayArr[0] integerValue]];
    [comp setHour:0];
    [comp setMinute:0];
    [comp setSecond:0];
    NSCalendar *myCal = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDate *startDate1 = [myCal dateFromComponents:comp];
    HKQuantityType *quantityType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
    NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
    dateComponents.day = 1;
    predicate = [HKQuery predicateForSamplesWithStartDate:startDate1 endDate:[NSDate date] options:HKQueryOptionNone];
    HKStatisticsCollectionQuery *collectionQuery = [[HKStatisticsCollectionQuery alloc] initWithQuantityType:quantityType quantitySamplePredicate:predicate options: HKStatisticsOptionCumulativeSum | HKStatisticsOptionSeparateBySource anchorDate:startDate1 intervalComponents:dateComponents];
    collectionQuery.initialResultsHandler = ^(HKStatisticsCollectionQuery *query, HKStatisticsCollection * __nullable result, NSError * __nullable error) {
        for (HKStatistics *statistic in result.statistics) {
            health.stepCount=[NSString stringWithFormat:@"%ld",(long)[statistic.sumQuantity doubleValueForUnit:[HKUnit countUnit]]];
            NSLog(@"update==%ld",(long)[statistic.sumQuantity doubleValueForUnit:[HKUnit countUnit]]);
        }
        [self updataWalkingRunning:toDayArr health:health];
    };
    [ self.healthStore executeQuery:collectionQuery];
    }
}
-(void)updataWalkingRunning:(NSArray*)dateArr health:(Health*)health{
    NSDate *startDate = [NSDate date];
    startDate=[NSDate distantPast];
    NSDateComponents *comp = [[NSDateComponents alloc]init];
    [comp setMonth:[dateArr[1] integerValue]];
    [comp setDay:[dateArr[2] integerValue]];
    [comp setYear:[dateArr[0] integerValue]];
    [comp setHour:0];
    [comp setMinute:0];
    [comp setSecond:0];
    NSCalendar *myCal = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDate *startDate1 = [myCal dateFromComponents:comp];
    HKQuantityType *quantityType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning];
    NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
    dateComponents.day = 1;
    NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:startDate1 endDate:[NSDate date] options:HKQueryOptionNone];
    HKStatisticsCollectionQuery *collectionQuery = [[HKStatisticsCollectionQuery alloc] initWithQuantityType:quantityType quantitySamplePredicate:predicate options: HKStatisticsOptionCumulativeSum | HKStatisticsOptionSeparateBySource anchorDate:startDate1 intervalComponents:dateComponents];
    collectionQuery.initialResultsHandler = ^(HKStatisticsCollectionQuery *query, HKStatisticsCollection * __nullable result, NSError * __nullable error) {
        for (NSInteger i=0; i<result.statistics.count; i++) {
            HKStatistics *statistic=result.statistics[i];
                double  kil=[statistic.sumQuantity doubleValueForUnit:[HKUnit mileUnit]]*1.6093;
                double time=kil*1000/1.2/60;
                double kcal=55*kil*1.036;
                health.kil= [NSString stringWithFormat:@"%.1f",kil];
                health.time=[NSString stringWithFormat:@"%ld",(long)time];
                health.kcal=[NSString stringWithFormat:@"%ld",(long)kcal];
            NSLog(@"update===%@",[NSString stringWithFormat:@"%.1f",kil]);
            NSLog(@"update===%@",[NSString stringWithFormat:@"%ld",(long)time]);
            NSLog(@"update===%@",[NSString stringWithFormat:@"%ld",(long)kcal]);
        };
        //[self.manager saveContext];
        [self upDataFlightsClimbed:dateArr health:health];
    };
    [ self.healthStore executeQuery:collectionQuery];
    
}
-(void)upDataFlightsClimbed:(NSArray*)dateArr health:(Health*)health{
    self.manager=[CoreDataManager manager];
    NSDate *startDate = [NSDate date];
    startDate=[NSDate distantPast];
    NSDateComponents *comp = [[NSDateComponents alloc]init];
    [comp setMonth:[dateArr[1] integerValue]];
    [comp setDay:[dateArr[2] integerValue]];
    [comp setYear:[dateArr[0] integerValue]];
    [comp setHour:0];
    [comp setMinute:0];
    [comp setSecond:0];
    NSCalendar *myCal = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDate *startDate1 = [myCal dateFromComponents:comp];
    HKQuantityType *quantityType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierFlightsClimbed];
    NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
    dateComponents.day = 1;
    NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:startDate1 endDate:[NSDate date] options:HKQueryOptionNone];
    HKStatisticsCollectionQuery *collectionQuery = [[HKStatisticsCollectionQuery alloc] initWithQuantityType:quantityType quantitySamplePredicate:predicate options: HKStatisticsOptionCumulativeSum | HKStatisticsOptionSeparateBySource anchorDate:startDate1 intervalComponents:dateComponents];
    collectionQuery.initialResultsHandler = ^(HKStatisticsCollectionQuery *query, HKStatisticsCollection * __nullable result, NSError * __nullable error) {
        for (NSInteger i=0; i<result.statistics.count; i++) {
            HKStatistics *statistic=result.statistics[i];
                    health.floor=[NSString stringWithFormat:@"%ld",(long)[statistic.sumQuantity doubleValueForUnit:[HKUnit countUnit]]];
            NSLog(@"update===%@",[NSString stringWithFormat:@"%ld",(long)[statistic.sumQuantity doubleValueForUnit:[HKUnit countUnit]]]);
        };
        [self.manager saveContext];
//         [[NSNotificationCenter defaultCenter] postNotificationName:@"createData" object:nil];
    };
    [ self.healthStore executeQuery:collectionQuery];
}
-(void)timeOfday{
    NSComparator cmptr = ^(id obj1, id obj2){
        if ([obj1 integerValue] > [obj2 integerValue]) {
            return (NSComparisonResult)NSOrderedDescending;
        }
        
        if ([obj1 integerValue] < [obj2 integerValue]) {
            return (NSComparisonResult)NSOrderedAscending;
        }
        return (NSComparisonResult)NSOrderedSame;
    };
      self.manager=[CoreDataManager manager];
    NSDate *startDate = [NSDate date];
    startDate=[NSDate distantPast];
    NSDateComponents *comp = [[NSDateComponents alloc]init];
    [comp setMonth:3];
    [comp setDay:1];
    [comp setYear:2016];
    [comp setHour:0];
    [comp setMinute:0];
    [comp setSecond:0];
    NSCalendar *myCal = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDate *startDate1 = [myCal dateFromComponents:comp];
    HKQuantityType *quantityType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
    NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
    dateComponents.hour = 3;
    NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:startDate1 endDate:[NSDate date] options:HKQueryOptionNone];
    HKStatisticsCollectionQuery *collectionQuery = [[HKStatisticsCollectionQuery alloc] initWithQuantityType:quantityType quantitySamplePredicate:predicate options: HKStatisticsOptionCumulativeSum | HKStatisticsOptionSeparateBySource anchorDate:startDate1 intervalComponents:dateComponents];
    collectionQuery.initialResultsHandler = ^(HKStatisticsCollectionQuery *query, HKStatisticsCollection * __nullable result, NSError * __nullable error) {
        NSMutableDictionary * dateDic=[NSMutableDictionary dictionary];
       
        for (HKStatistics *statistic in result.statistics) {
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat:@"YYYY-MM-dd"];
            NSString *dateString = [dateFormatter stringFromDate:statistic.startDate];
            [dateFormatter setDateFormat:@"HH"];
            NSString *shiString = [dateFormatter stringFromDate:statistic.startDate];
            if ([[dateDic allKeys] containsObject:dateString]) {
                NSMutableDictionary * timeDic=dateDic[dateString];
                if ([[timeDic allKeys ] containsObject:shiString]) {
                timeDic[shiString]=[NSString stringWithFormat:@"%ld",(long)[statistic.sumQuantity doubleValueForUnit:[HKUnit countUnit]]];
                }
            }else{
                 NSMutableDictionary * stepDic=[NSMutableDictionary dictionaryWithDictionary:@{@"06":@"0",@"09":@"0",@"12":@"0",@"15":@"0",@"18":@"0",@"21":@"0"}];
                [dateDic setObject:stepDic forKey:dateString];
                if ([[stepDic allKeys ] containsObject:shiString]) {
                    stepDic[shiString]=[NSString stringWithFormat:@"%ld",(long)[statistic.sumQuantity doubleValueForUnit:[HKUnit countUnit]]];
                }
            }

        }
        for (NSString * tempStr in [dateDic allKeys]) {
            TimeOfDay * timeOfDay=[NSEntityDescription insertNewObjectForEntityForName:@"TimeOfDay" inManagedObjectContext:self.manager.managedObjectContext];
            timeOfDay.date=tempStr;
            NSMutableDictionary * tempDic=dateDic[tempStr];
            NSArray * keyArr=  [tempDic allKeys];
                            NSArray *array = [keyArr sortedArrayUsingComparator:cmptr];
                            NSMutableArray * valueArr=[NSMutableArray array];
                            for (NSString * num in array) {
            
                                [valueArr addObject:tempDic[num]];
                            }
                            NSString *stepCountStr = [valueArr componentsJoinedByString:@","];
            timeOfDay.stepCount=stepCountStr;
            [self.manager saveContext];
           // NSLog(@"================%@================%@",tempStr,stepCountStr);
        }
        
    };
    [ self.healthStore executeQuery:collectionQuery];
}
-(void)createStepCount{
    self.manager=[CoreDataManager manager];
    self.healthDataArr=[NSMutableArray array];
    NSDate *startDate = [NSDate date];
    startDate=[NSDate distantPast];
    NSDateComponents *comp = [[NSDateComponents alloc]init];
    [comp setMonth:3];
    [comp setDay:1];
    [comp setYear:2016];
    [comp setHour:0];
    [comp setMinute:0];
    [comp setSecond:0];
    NSCalendar *myCal = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDate *startDate1 = [myCal dateFromComponents:comp];
    HKQuantityType *quantityType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
    NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
    dateComponents.day = 1;
    NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:startDate1 endDate:[NSDate date] options:HKQueryOptionNone];
    HKStatisticsCollectionQuery *collectionQuery = [[HKStatisticsCollectionQuery alloc] initWithQuantityType:quantityType quantitySamplePredicate:predicate options: HKStatisticsOptionCumulativeSum | HKStatisticsOptionSeparateBySource anchorDate:startDate1 intervalComponents:dateComponents];
    collectionQuery.initialResultsHandler = ^(HKStatisticsCollectionQuery *query, HKStatisticsCollection * __nullable result, NSError * __nullable error) {
        for (HKStatistics *statistic in result.statistics) {
            NSTimeZone *zone = [NSTimeZone systemTimeZone];
            NSInteger startInterval = [zone secondsFromGMTForDate:statistic.startDate];
            NSDate *startDate = [statistic.startDate dateByAddingTimeInterval: startInterval];
            Health * health=[NSEntityDescription insertNewObjectForEntityForName:@"Health" inManagedObjectContext:self.manager.managedObjectContext];
            health.stepCount=[NSString stringWithFormat:@"%ld",(long)[statistic.sumQuantity doubleValueForUnit:[HKUnit countUnit]]];
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat:@"YYYY-MM-dd"];
            NSString *dateString = [dateFormatter stringFromDate:startDate];
            health.date=dateString;
            [self.healthDataArr addObject:health];
            [self.manager saveContext];
        }
        [self createWalkingRunning];
    };
    [ self.healthStore executeQuery:collectionQuery];
}
-(void)createWalkingRunning{
    self.manager=[CoreDataManager manager];
    NSDate *startDate = [NSDate date];
    startDate=[NSDate distantPast];
    NSDateComponents *comp = [[NSDateComponents alloc]init];
    [comp setMonth:3];
    [comp setDay:1];
    [comp setYear:2016];
    [comp setHour:0];
    [comp setMinute:0];
    [comp setSecond:0];
    NSCalendar *myCal = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDate *startDate1 = [myCal dateFromComponents:comp];
    HKQuantityType *quantityType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning];
    NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
    dateComponents.day = 1;
    NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:startDate1 endDate:[NSDate date] options:HKQueryOptionNone];
    HKStatisticsCollectionQuery *collectionQuery = [[HKStatisticsCollectionQuery alloc] initWithQuantityType:quantityType quantitySamplePredicate:predicate options: HKStatisticsOptionCumulativeSum | HKStatisticsOptionSeparateBySource anchorDate:startDate1 intervalComponents:dateComponents];
    collectionQuery.initialResultsHandler = ^(HKStatisticsCollectionQuery *query, HKStatisticsCollection * __nullable result, NSError * __nullable error) {
        for (NSInteger i=0; i<result.statistics.count; i++) {
            HKStatistics *statistic=result.statistics[i];
            Health * health=self.healthDataArr[i];
            NSTimeZone *zone = [NSTimeZone systemTimeZone];
            NSInteger startInterval = [zone secondsFromGMTForDate:statistic.startDate];
            NSDate *startDate = [statistic.startDate dateByAddingTimeInterval: startInterval];
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat:@"YYYY-MM-dd"];
            NSString *dateString = [dateFormatter stringFromDate:startDate];
            if ([health.date isEqualToString:dateString]) {
                double  kil=[statistic.sumQuantity doubleValueForUnit:[HKUnit mileUnit]]*1.6093;
                double time=kil*1000/1.2/60;
                double kcal=55*kil*1.036;
                health.kil= [NSString stringWithFormat:@"%.1f",kil];
                health.time=[NSString stringWithFormat:@"%ld",(long)time];
                health.kcal=[NSString stringWithFormat:@"%ld",(long)kcal];
            }
        };
        [self.manager saveContext];
        [self createFlightsClimbed];
    };
    [ self.healthStore executeQuery:collectionQuery];
    
}
-(void)createFlightsClimbed{
    self.manager=[CoreDataManager manager];
    NSDate *startDate = [NSDate date];
    startDate=[NSDate distantPast];
    NSDateComponents *comp = [[NSDateComponents alloc]init];
    [comp setMonth:3];
    [comp setDay:1];
    [comp setYear:2016];
    [comp setHour:0];
    [comp setMinute:0];
    [comp setSecond:0];
    NSCalendar *myCal = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDate *startDate1 = [myCal dateFromComponents:comp];
    HKQuantityType *quantityType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierFlightsClimbed];
    NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
    dateComponents.day = 1;
    NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:startDate1 endDate:[NSDate date] options:HKQueryOptionNone];
    HKStatisticsCollectionQuery *collectionQuery = [[HKStatisticsCollectionQuery alloc] initWithQuantityType:quantityType quantitySamplePredicate:predicate options: HKStatisticsOptionCumulativeSum | HKStatisticsOptionSeparateBySource anchorDate:startDate1 intervalComponents:dateComponents];
    collectionQuery.initialResultsHandler = ^(HKStatisticsCollectionQuery *query, HKStatisticsCollection * __nullable result, NSError * __nullable error) {
        for (NSInteger i=0; i<result.statistics.count; i++) {
            HKStatistics *statistic=result.statistics[i];
            NSTimeZone *zone = [NSTimeZone systemTimeZone];
            NSInteger startInterval = [zone secondsFromGMTForDate:statistic.startDate];
            NSDate *startDate = [statistic.startDate dateByAddingTimeInterval: startInterval];
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat:@"YYYY-MM-dd"];
            NSString *dateString = [dateFormatter stringFromDate:startDate];
            for (Health * health in self.healthDataArr) {
                if ([health.date isEqualToString:dateString]) {
                    health.floor=[NSString stringWithFormat:@"%ld",(long)[statistic.sumQuantity doubleValueForUnit:[HKUnit countUnit]]];
                    continue;
                }
            }
        };
          [self timeOfday];
        [self.manager saveContext];
//        [[NSNotificationCenter defaultCenter] postNotificationName:@"createData" object:nil];
    };
    [ self.healthStore executeQuery:collectionQuery];
}

@end
